package com.angel.components.editor
{

	import com.adobe.linguistics.spelling.SpellChecker;
	import com.adobe.linguistics.spelling.SpellUI;
	import com.adobe.linguistics.spelling.SpellingDictionary;
	import com.angel.components.editor.controls.TitleCaseFormatter;
	import com.angel.components.editor.controls.UpperCaseFormatter;
	import com.angel.thirds.components.hillelcoren.autoComplete.PromptTextInput;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.ui.ContextMenu;
	
	import mx.containers.ControlBar;
	import mx.controls.Label;
	import mx.controls.RichTextEditor;
	import mx.controls.ToggleButtonBar;
	
	public class HTMLEditor extends RichTextEditor {
		
		[Bindable]
		private var xhtmlText:String;
		[Bindable]
		private var _contextMenu:ContextMenu;
		[Bindable]
		private var _newdict:SpellingDictionary = new SpellingDictionary();
		[Bindable]
		private var sp:SpellChecker = new SpellChecker();

		
		public override function initialize():void {
			super.initialize();
			super.showControlBar = false;
			super.addEventListener(MouseEvent.MOUSE_OUT,	rollOutEvent);
			super.addEventListener(MouseEvent.MOUSE_OVER,	rollOverEvent);
			super.addEventListener(Event.CHANGE,			onChangeEvent);
			this.initializeControls();
			this.initializeContextMenu();
		}
	/**
	 * Context menu:
	 * http://blog.flexexamples.com/2007/12/31/creating-a-custom-context-menu-on-a-richtexteditor-control-in-flex/
	 * 
	 * Spell checker:
	 * http://blogs.adobe.com/cgi-bin/mt/mt-search.cgi?IncludeBlogs=305&tag=Squiggly&limit=20
	 * 
	 * Supported Tags:
	 * http://www.flexer.info/2008/05/08/html-tags-and-attributes-supported-by-flash-player/
	 * 
	 * Styles:
	 * http://www.rubenswieringa.com/code/as3/flex/HTMLStyle/
	 * http://www.flashtexteditor.com/flexdemo/full/
	 * 
	 */
		protected function initializeContextMenu():void {
			_contextMenu = new ContextMenu();
            _contextMenu.hideBuiltInItems();
			//_contextMenu.customItems.push(showSelection);
			//_contextMenu.customItems.push(upperCase);
            //_contextMenu.customItems.push(lowerCase);
            contextMenu = _contextMenu;
            
		}
		protected function initializeControls():void {
			/** Initialize Spelling Checker. */
			SpellUI.enableSpelling(this, 'usa.zwl');

			/** Initialize Title Case Formatter. */
			this.addFindReplaceControl();
			/** Initialize Title Case Formatter. */
			this.addTitleCaseFormatterControl();
			/** Initialize Upper Case Formatter. */
			this.addUpperCaseFormaterControl();
		}
		
		private function addFindReplaceControl():void {
			var findReplaceButtonBar:ControlBar = new ControlBar();
			var buscarLabel:Label = new Label();
			buscarLabel.text = "Buscar: ";
			
			var buscarInput:PromptTextInput = new PromptTextInput();
			buscarInput.prompt = 'Escribir la frase a buscar...';
			
			
			findReplaceButtonBar.addChild(buscarLabel);
			findReplaceButtonBar.addChild(buscarInput);
			
			this.addControl(findReplaceButtonBar);
		}

		private function addTitleCaseFormatterControl():void {
			var titleCaseFormatter:TitleCaseFormatter = new TitleCaseFormatter();
			titleCaseFormatter.target = this;
			this.addControl(titleCaseFormatter);
		}
		
		private function addUpperCaseFormaterControl():void{
			var upperCase:UpperCaseFormatter = new UpperCaseFormatter();
			upperCase.target = this;
			this.addControl(upperCase);
		}
		
		protected function addControl(control:DisplayObject):void {
			var a:Array = toolbar.getChildren();
			toolbar.addChild(control);
		}
		
		protected function rollOutEvent(event:MouseEvent):void {
			super.showControlBar = false;
		}
		
		protected function rollOverEvent(event:MouseEvent):void {
			super.showControlBar = true;
		}
		
		protected function onChangeEvent(event:Event):void {
	         update();
	    }
	
	    private function update():void {
	        xhtmlText = richTextEditorToHtml( super.htmlText );
	    }

		protected function cleanATag(str:String):String {
			var pattern:RegExp;
			var str:String;
			pattern = /<A HREF/gi;
			str = str.replace(pattern, "<a href");
			pattern = /<\/A>/gi;
			str = str.replace(pattern, "<\/a>");
			pattern= /TARGET="_blank"/gi;
			str = str.replace(pattern, "rel=\"external\" ");   
			return str;
		}


		public function cleanHTML(str:String):String {
	        var pattern:RegExp;
	        var str:String;
	
	        pattern = /COLOR=\"(.*?)\"/gi;
	        str = str.replace(pattern, "color:$1;");
	        pattern = /SIZE=\"(.*?)\"/gi;
	        str = str.replace(pattern, "font-size:$1px;");
	        pattern = /FACE=\"(.*?)\"/gi;
	        str = str.replace(pattern, "font-family:$1;");
	        pattern = /ALIGN=\"(.*?)\"/gi;
	        str = str.replace(pattern, "text-align:$1;");
	        
	        //format <font> tag
	        pattern = /<FONT STYLE/gi;
	        str = str.replace(pattern, "<font style");
	        pattern = /<\/FONT.*?>/gi;
	        str = str.replace(pattern, "<\/font>");
	        
	        //format <p> tag
	        pattern = /<P STYLE/gi;
	        str = str.replace(pattern, "<p style");
	        pattern = /<\/P>/gi;
	        str = str.replace(pattern, "<\/p>");
	        
	        //format <li> tag
	        pattern= /<LI>/gi;
	        str = str.replace(pattern, "<li>");
	        pattern= /<\/LI>/gi;
	        str = str.replace(pattern, "</li>");
	        
	        //format <ul> tag
	        pattern= /<UL>/gi;
	        str = str.replace(pattern, "<ul>");
	        pattern= /<\/UL>/gi;
	        str = str.replace(pattern, "</ul>");
	
	   
	
	
	        //format alignment in styles tag
	        pattern = /text-align: RIGHT/gi;
	        str = str.replace(pattern, "text-align:right");
	        pattern = /text-align: LEFT/gi;
	        str = str.replace(pattern, "text-align:left");
	        pattern = /text-align: CENTER/gi;
	        str = str.replace(pattern, "text-align:center");
	        pattern = /text-align: JUSTIFY/gi;
	        str = str.replace(pattern, "text-align:justify");
	        
	        //format <a> tag
	        
	        //created a seperate function that way i can override it, and
	        //put in my own stuff in the class that is extending it.
	        //i could do this with all of the tags, but for now all i need is the 
	        //a href tag.
	        str = cleanATag(str);
	        
	        pattern = /<I>/gi;
	        str = str.replace(pattern, "<em>");
	        pattern = /<\/I>/gi;
	        str = str.replace(pattern, "</em>");
	        pattern = /<B>/gi;
	        str = str.replace(pattern, "<strong>");
	        pattern = /<\/B>/gi;
	        str = str.replace(pattern, "</strong>");
	        pattern = /<U>/gi;
	        str = str.replace(pattern, "<u>");
	        pattern = /<\/U>/gi;
	        str = str.replace(pattern, "</u>");
	        
	        //this is to fix a bug
	        //for some reason there is a u tag showing up? wtf
	        pattern = /<U\/>/gi;
	        str = str.replace(pattern, "");
	        
	        return str;
		}
    
		private function richTextEditorToHtml(str:String):String {
	        // Create XML document
	        var xml:XML = XML("<BODY>"+str+"</BODY>");
	
	        // temporary
	        var t1:XML;
	        var t2:XML;
	        
	        // Remove all TEXTFORMAT
	        for( t1 = xml..TEXTFORMAT[0]; t1 != null; t1 = xml..TEXTFORMAT[0] ) {
	            t1.parent().replace( t1.childIndex(), t1.children() );
	        }
	        
	        // Find all ALIGN
	        for each ( t1 in xml..@ALIGN ) {
	            t2 = t1.parent();
	            t2.@STYLE = "text-align: " + t1 + "; " + t2.@STYLE;
	            delete t2.@ALIGN;
	        }
	         
	        // Find all FACE
	        for each ( t1 in xml..@FACE ) {
	            t2 = t1.parent();
	            t2.@STYLE = "font-family: " + t1 + "; " + t2.@STYLE;
	            delete t2.@FACE;
	        }
	        
	        // Find all SIZE 
	        for each ( t1 in xml..@SIZE ) {
	            t2 = t1.parent();
	            t2.@STYLE = "font-size: " + t1 + "px; " + t2.@STYLE;
	            delete t2.@SIZE;
	        }
	
	        // Find all COLOR 
	        for each ( t1 in xml..@COLOR ) {
	            t2 = t1.parent();
	            t2.@STYLE = "color: " + t1 + "; " + t2.@STYLE;
	            delete t2.@COLOR;
	        }
	        
	        // Find all LETTERSPACING 
	        for each ( t1 in xml..@LETTERSPACING ) {
	            t2 = t1.parent();
	            t2.@STYLE = "letter-spacing: " + t1 + "px; " + t2.@STYLE;
	            delete t2.@LETTERSPACING;
	        }
	        
	        // Find all KERNING
	        for each ( t1 in xml..@KERNING ) {
	            t2 = t1.parent();
	            // ? css 
	            delete t2.@KERNING;
	        }
	        
	
	        return cleanHTML(xml.children().toXMLString());
		}

	}	
}